package com.ihighest.app.infox.activity;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.ListViewKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.ReplyCommentAdapter;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 评论详情界面
 * 
 * @author lkx Created at 2015-10-23 下午7:06:55
 * @version 1.0
 */
public class CommentDetailsActivity extends BaseActivity {
	private ActivityTitle title;
	private String commentId;
	private String userName;
	private String uesrImg;
	private String content;
	private long time;
	private int praises;
	private int reply;
	private ImageView userImg;
	private TextView name, commentContent, commentData, commentReply, commentThump;
	private ListView replyList;
	private PopupWindow mPopupWindow;
	private EditText writeComment;
	private String type = "1";// 回复类型，默认为回复评论
	private String replyId;// 回复id，默认回复品论
	private String replyName = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_comment_detail);
		initView();
	}

	/**
	 * 
	 * 初始化绑定
	 * 
	 * @author lkx Created at 2015-10-23 下午6:05:01
	 */
	@SuppressWarnings("deprecation")
	private void initView() {
		title = (ActivityTitle) findViewById(R.id.commentDetailsTitle);
		title.setTitle("详情");
		title.setViewVersible(title.titleBack);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		userImg = (ImageView) findViewById(R.id.commentUserImg);
		name = (TextView) findViewById(R.id.commentUserName);
		commentContent = (TextView) findViewById(R.id.commentContent);
		commentData = (TextView) findViewById(R.id.commentDate);
		commentThump = (TextView) findViewById(R.id.thumpUp);
		commentReply = (TextView) findViewById(R.id.commentReply);
		replyList = (ListView) findViewById(R.id.replyList);
		commentId = getIntent().getStringExtra("id");
		userName = getIntent().getStringExtra("commentName");
		uesrImg = getIntent().getStringExtra("commentImg");
		content = getIntent().getStringExtra("commentContent");
		time = getIntent().getLongExtra("commentTime", 0);
		praises = getIntent().getIntExtra("praises", 0);
		reply = getIntent().getIntExtra("commentsReply", 0);
		name.setText(userName);
		commentContent.setText(content);
		commentData.setText(AppKit.timeToBeforeStr(time));
		commentReply.setText(reply + "");
		commentThump.setText(praises + "");
		Drawable drawable = getResources().getDrawable(R.drawable.infox_person_no_icon);
		// DisplayImageOptions defaultOptions = new
		// DisplayImageOptions.Builder().showImageForEmptyUri(drawable).showImageOnFail(drawable)
		// .showImageOnLoading(drawable).cacheInMemory(true).cacheOnDisc(true).build();
		AppKit.SetNormalImg(uesrImg, userImg);
		// ImageLoader.getInstance().displayImage(uesrImg, userImg,
		// defaultOptions);
		initCommentPupoVindow();
		replyId = commentId;
		findViewById(R.id.writReply).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				type = "1";
				writeComment.setHint("写评论...");
				isReply();

			}

			/**
			 * 是否可以回复
			 * 
			 * 
			 * @author lkx Created at 2015-10-24 上午10:10:02
			 */
			private void isReply() {
				try {
					if (SharedPreferencesKit.getJsonObject(CommentDetailsActivity.this, Const.CategoryConfig).getBoolean(
							"ac.comment_need_login")) {
						// 如果评论需要登录
						if (!TextUtils.isEmpty(SharedPreferencesKit.getString(CommentDetailsActivity.this, Const.SP_KEY_USER_ID))) {
							if (SharedPreferencesKit.getJsonObject(CommentDetailsActivity.this, Const.CategoryConfig).getBoolean(
									"ac.comment_can_reply")) {
								showPupop();
							} else {
								ToastKit.showShort(CommentDetailsActivity.this, "暂不允许回复");
							}
						} else {
							ToastKit.showShort(CommentDetailsActivity.this, Const.UN_LOGIN_ALERT);
						}
					} else {
						// 如果评论不需要登录
						showPupop();
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		initData(1, 0);
	}

	/**
	 * 获取回复数据
	 * 
	 * @param page
	 *            页数 第一次为1
	 * @param time
	 *            时间戳 第一次不需要该参数
	 * 
	 * @author lkx Created at 2015-10-23 下午7:06:58
	 */
	private void initData(int page, long time) {
		ApiParam param = ApiParam.create();
		param.addParam("id", commentId).addParam("page", page);
		if (time != 0) {
			param.addParam("time", time);
		}

		Api.get("comment/replys", param, new ApiCallback(CommentDetailsActivity.this) {

			@Override
			public void handleSuccess(ApiResult result) {
				final JSONArray array = result.getDatas();
				commentReply.setText(result.getDatas().length() + "");
				replyList.setAdapter(new ReplyCommentAdapter(CommentDetailsActivity.this, result.getDatas()));
				// ListViewKit.setListViewHeightBasedOnChildren(replyList);
				replyList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						try {

							if (SharedPreferencesKit.getJsonObject(CommentDetailsActivity.this, Const.CategoryConfig).getBoolean(
									"ac.comment_need_login")) {
								// 如果评论需要登录
								if (!TextUtils.isEmpty(SharedPreferencesKit.getString(CommentDetailsActivity.this, Const.SP_KEY_USER_ID))) {
									// 用户已经登录
									if (SharedPreferencesKit.getJsonObject(CommentDetailsActivity.this, Const.CategoryConfig).getBoolean(
											"ac.reply_can_reply")) {
										// 回复可以回复
										type = "2";
										replyId = array.getJSONObject(arg2).getString("id");
										replyName = array.getJSONObject(arg2).getString("name");
										writeComment.setHint("回复：" + replyName + ":");

										showPupop();
									} else {
										ToastKit.showShort(CommentDetailsActivity.this, "暂不允许回复");
									}
								} else {
									ToastKit.showShort(CommentDetailsActivity.this, Const.UN_LOGIN_ALERT);
								}
							} else {
								// 如果评论不需要登录
								type = "2";
								replyId = array.getJSONObject(arg2).getString("id");
								replyName = array.getJSONObject(arg2).getString("name");
								writeComment.setHint("回复：" + replyName + ":");
								showPupop();
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub

			}
		}, CommentDetailsActivity.this);

	}

	private void initCommentPupoVindow() {
		// final InitShare share = new
		// InitShare(InformationalContentActivity.this);
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_activity_commentdetail_write_popup, null);

		writeComment = (EditText) popupWindow.findViewById(R.id.writeReply);
		// 创建一个PopupWindow
		// 参数1：contentView 指定PopupWindow的内容
		// 参数2：width 指定PopupWindow的width
		// 参数3：height 指定PopupWindow的height
		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */

		mPopupWindow.setFocusable(true);
		mPopupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popupWindow.findViewById(R.id.reply).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(writeComment.getText().toString().trim())) {
					ToastKit.showShort(CommentDetailsActivity.this, "回复内容不能为空！");
				} else {
					commitReply(writeComment.getText().toString().trim());
				}
				writeComment.setText("");
			}

			/**
			 * 提交回复
			 * 
			 * 
			 * @author lkx Created at 2015-10-23 下午9:00:01
			 */
			private void commitReply(String content) {
				ApiParam param = ApiParam.create();
				param.addParam("id", replyId);
				param.addParam("type", type);
				param.addParam("content", content);
				Api.post("comment/reply", param, new ApiCallback(CommentDetailsActivity.this) {

					@Override
					public void handleSuccess(ApiResult result) {
						// TODO Auto-generated method stub
						mPopupWindow.dismiss();
						InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						manager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

						initData(1, 0);
					}

					@Override
					public void handleFailure(Exception e, String msg) {
						// TODO Auto-generated method stub

					}
				}, CommentDetailsActivity.this);
			}
		});
	}

	/**
	 * 显示pupop
	 * 
	 * 
	 * @author lkx Created at 2015-10-16 下午3:44:17
	 */
	private void showPupop() {

		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();

		} else {
			mPopupWindow.showAtLocation(findViewById(R.id.commentDetail), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		}

	}

}
